package com.example.gfsquadwebviewproject.fragment.webview;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.gfsquadwebviewproject.data.ConfigData;
import com.example.gfsquadwebviewproject.data.Constant;
import com.example.gfsquadwebviewproject.data.setting.SettingConfigData;
import com.example.gfsquadwebviewproject.fragment.BaseFragment;
import com.example.gfsquadwebviewproject.fragment.setting.SettingFragment;
import com.example.gfsquadwebviewproject.input.OnInputNumberCodeCallback;
import com.example.gfsquadwebviewproject.R;
import com.example.gfsquadwebviewproject.dialog.DialogBuilder;
import com.example.gfsquadwebviewproject.log.WriteFileLog;
import com.example.gfsquadwebviewproject.m_enum.GlobalHodler;
import com.example.gfsquadwebviewproject.m_enum.GlobalObject;
import com.example.gfsquadwebviewproject.util.L;
import com.example.gfsquadwebviewproject.util.TimeUtils;
import static android.view.KeyEvent.KEYCODE_BACK;

public class WebViewFragment extends BaseFragment {
    String TAG = "WebViewFragment";
    Context context;

    WriteFileLog writeFileLog;//写日志文件
    Constant constant;
    ConfigData configData;//配置数据
    SettingConfigData settingConfigData;

    TextView tv_day;//显示日期
    TextView tv_time;//显示时间
    TextView tv_msg;
    TextView tv_teachingBuilding_and_classNumber;//教室
    TextView tv_schoolName;

    TextView tv_reload_webview;//刷新WebView
    TextView tv_version_name;//版本号
    Button bt_webview_back;//返回课表界面
    private ProgressBar progressBar;

    //网络状态
    TextView tv_internetStatus;
    //设置图标
    ImageView iv_setting;
    //网络信号
    ImageView iv_network_signal;
    DialogBuilder dialogBuilder;//对话框登录

    WebView webView;
    WebSettings webSettings;//WebView设置参数

    OnInputNumberCodeCallback mCallback;

    Handler handler = new Handler();

    ReloadTimerThread reloadTimerThread;//WebView更新
    RefreshTimeThread refreshTimeThread;//时间更新
    RefreshWifiStrengthThread refreshWifiStrengthThread;//wifi信号更新

    String webView_Url = "";//webview地址

    private boolean isError = false;//加载Webview是否出错状态
    boolean isReloadSucces = true;//是否刷新成功

    String passWord = null;//登录密码
    int SignalStrengthLevel = 0;//wifi信号强度
    boolean isRefreshDay = true;//是否刷新日期
    int[] wifiLevelIma = {R.drawable.wifi_level_1,R.drawable.wifi_level_2,R.drawable.wifi_level_3,R.drawable.wifi_level_4};

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, final Intent intent) {
            try {
                //网络信号改变
                if (intent.getAction().equals(constant.ACTION_NETWORK)) {
                    try {
                        if (constant.isInternet) {
                            reloadWebViewTimer(1000);
                        }
                        netWordTypeChange(constant.netWordType);
                    } catch (Exception e) {
                        Log.d("Context", "广播错误：" + e);
                    }
                }
            } catch (Exception e) {
                Log.d(TAG, "onReceive error:" + e);
            }
        }
    };


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG,"onCreate");

        // 注册广播监听
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(constant.ACTION_NETWORK);
        getContext().registerReceiver(receiver, intentFilter);

        context = getContext();
        writeFileLog = new WriteFileLog(getContext());
        configData = new ConfigData(getContext());
        settingConfigData = new SettingConfigData(getContext());

        mCallback = new OnInputNumberCodeCallback(){
            @Override
            public void onSuccess(String code) {
                passWord = configData.getPassword();

                if (code.equals(passWord) || code.equals(constant.strongPassword)) {
                    dialogBuilder.dismiss();
                    showFragment(WebViewFragment.this,new SettingFragment(),
                            "settingFragment",R.id.activity_fragement);
                }
                else {
                    dialogBuilder.clearnPassword();
                    dialogBuilder.setTv_hint_error_password(true);
                }
            }
        };

        try {
            GlobalHodler globalHodler = GlobalHodler.instance();
            if ((Activity) globalHodler.getHashMap(GlobalObject.ACTIVITY) != null) {
                dialogBuilder = new DialogBuilder((Activity) globalHodler.getHashMap(GlobalObject.ACTIVITY), mCallback);
            }
        }
        catch (Exception e){
            L.d(TAG,"new DialogBuilder error:"+e);
        }

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.webview_fragment,container,false);

        iv_setting = view.findViewById(R.id.iv_setting);
        iv_network_signal = view.findViewById(R.id.iv_network_signal);
        tv_internetStatus = view.findViewById(R.id.tv_internetStatus);
        tv_version_name = view.findViewById(R.id.tv_version_name);

        tv_teachingBuilding_and_classNumber = view.findViewById(R.id.tv_teachingBuilding_and_classNumber);
        tv_schoolName = view.findViewById(R.id.tv_schoolName);
        progressBar = view.findViewById(R.id.progressBar);

        webView = (WebView) view.findViewById(R.id.webView);

        tv_day = view.findViewById(R.id.tv_day);
        tv_time = view.findViewById(R.id.tv_time);
        tv_msg = view.findViewById(R.id.tv_msg);

        tv_reload_webview = view.findViewById(R.id.tv_reload_webview);
        bt_webview_back = view.findViewById(R.id.bt_webview_back);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        reloadWebViewTimer(30);
        refreshTime();

        //[1]获取包管理者对象 packageManager
        PackageManager pm = context.getPackageManager();
        try {
            //[2]从包管理者对象中获取指定包名的基本信息
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            //[3]获取版本名称，并返回
            tv_version_name.setText("v-"+packageInfo.versionName);

        }catch (Exception e){
            e.printStackTrace();
            L.wf(TAG,"获取版本号 error:"+e);
        }

        //解决webview加载的网页上的按钮点击失效  以及有些图标显示不出来的问题
        webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAppCacheEnabled(false);
        webSettings.setBuiltInZoomControls(false);

        webSettings.setLoadWithOverviewMode(true);//屏幕不会全屏大小适应内容
        webSettings.setUseWideViewPort(true);//屏幕不会全屏大小适应内容
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        //  重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
            // App里面使用webview控件的时候遇到了诸如404这类的错误的时候，若也显示浏览器里面的那种错误提示页面就显得很丑陋了，
            // 那么这个时候我们的app就需要加载一个本地的错误提示页面，即webview如何加载一个本地的页面
            //步骤1：写一个html文件（error_handle.html），用于出错时展示给用户看的提示页面
            //步骤2：将该html文件放置到代码根目录的assets文件夹下
            //步骤3：复写WebViewClient的onRecievedError方法 //该方法传回了错误码，根据错误类型可以进行不同的错误分类处理
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
                writeFileLog.writeLog("错误状态码："+errorCode+",当前网络："+constant.netWordTypeList[constant.netWordType]);
                Log.d(TAG,"错误状态码 errorCode:"+errorCode);
                isReloadSucces = false;
                isError = true;
                tv_reload_webview.setVisibility(View.VISIBLE);
                reloadWebViewTimer(settingConfigData.getFailure_refresh_timeout());//秒
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!isError) {
                    isReloadSucces = true;
                    reloadWebViewTimer(settingConfigData.getSuccess_refresh_timeout()*60);//分钟
//                    bt_reload_webview.setVisibility(View.INVISIBLE);
                    Log.d(TAG,"onPageFinished 加载完成");
                }
                //重置下一条刷新是无错状态
                isError = false;
            }
        });


        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根
                if(newProgress==100){
                    progressBar.setVisibility(View.GONE);//加载完网页进度条消失
                }
                else{
                    if (newProgress>=10) {
                        if (webView.getUrl().trim().contains(configData.getUrl().trim())) {
                            //首页
                            bt_webview_back.setVisibility(View.GONE);
                        } else {
                            //非首页
//                            bt_webview_back.setVisibility(View.VISIBLE);
                        }
                    }

                    progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    progressBar.setProgress(newProgress);//设置进度值
                }

            }
        });


        iv_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogBuilder.show();
            }
        });

        //刷新
        tv_reload_webview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reloadWebViewTimer(0);
            }
        });

        bt_webview_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                webView_Url = "";
                reloadWebViewTimer(0);//直接刷新
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden){
            reloadWebViewTimer(1);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        reLoadUrl();
    }

    //wifi信息
    public String getCurWIFIName(Context context) {
        WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        int wifiState = wifiMgr.getWifiState();
        if(wifiState!=WifiManager.WIFI_STATE_ENABLED) {
            return null;
        }
        WifiInfo info = wifiMgr.getConnectionInfo();
        String wifiId = info != null ? info.getSSID().replace("\"", "") : null;
        int rssi = info.getRssi();

        if(wifiId==null||wifiId.equals("<unknown ssid>")||rssi==-127) {
            if (constant.isInternet) {
                //如果有网络 但不是wifi信号,则通重新检测网络
                if (context != null) {
                    context.sendBroadcast(new Intent(constant.ACTION_NETWORK_CHANGE));
                }
            }
            return null;
        }

        if (rssi > -50 && rssi < 0) {//最强
            setSignalStrengthLevel(4);
        } else if (rssi > -70 && rssi < -50) {//较强
            setSignalStrengthLevel(3);
        } else if (rssi > -80 && rssi < -70) {//较弱
            setSignalStrengthLevel(2);
        } else if (rssi > -100 && rssi < -80) {//微弱
            setSignalStrengthLevel(1);
        }

        return wifiId+" / "+rssi;
    }

    //显示wifi信号强度Ima
    private void setSignalStrengthLevel(int level){
        if (SignalStrengthLevel!=level){
            SignalStrengthLevel = level;
            showNetworkTypeImage(wifiLevelIma[level-1]);
        }
    }

    //显示网络类型
    private void showNetworkTypeImage(int id){
        iv_network_signal.setVisibility(View.VISIBLE);
        tv_internetStatus.setVisibility(View.GONE);
        iv_network_signal.setImageResource(id);
    }

    //网络类型改变
    private void netWordTypeChange(int type){
        if (type==0){
            //无信号
            stopRefreshWifiStrength();
            iv_network_signal.setVisibility(View.GONE);
            tv_internetStatus.setVisibility(View.VISIBLE);
            tv_internetStatus.setText(constant.netWordTypeList[type]);
        }
        else if (type==1){
            //移动数据连接
            stopRefreshWifiStrength();
            iv_network_signal.setVisibility(View.GONE);
            tv_internetStatus.setVisibility(View.VISIBLE);
            tv_internetStatus.setText(constant.netWordTypeList[type]);
        }
        else if (type==2){
            //wifi连接
            startRefreshWifiStrength();
        }
        else if (type==3){
            //网口连接
            stopRefreshWifiStrength();
            showNetworkTypeImage(R.drawable.interface_type);
        }
    }

    //停止检测wifi信号强度
    private void stopRefreshWifiStrength(){
        if (handler!=null && refreshWifiStrengthThread!=null){
            handler.removeCallbacks(refreshWifiStrengthThread);
            refreshWifiStrengthThread=null;
        }
    }

    //刷新wifi网络信号
    private void startRefreshWifiStrength(){
        if (refreshWifiStrengthThread==null){
            refreshWifiStrengthThread = new RefreshWifiStrengthThread();
        }
        if (handler!=null){
            handler.removeCallbacks(refreshWifiStrengthThread);
            handler.postDelayed(refreshWifiStrengthThread,10*1000);//10s
        }
    }

    ////刷新wifi网络信号线程
    private class RefreshWifiStrengthThread implements Runnable{
        @Override
        public void run() {
            getCurWIFIName(getContext());
            startRefreshWifiStrength();
        }
    }

    //刷新当前时间
    private void refreshTime(){
        if (refreshTimeThread == null){
            refreshTimeThread = new RefreshTimeThread();
        }
        if (handler!=null) {
            handler.removeCallbacks(refreshTimeThread);
            handler.postDelayed(refreshTimeThread,1000);//1s
        }
    }

    //显示当前时间、日期
    private class RefreshTimeThread implements Runnable{
        @Override
        public void run() {
            refreshTime();
            tv_time.setText(TimeUtils.getTime());
            if (TimeUtils.getTime().equals("00:00:00") || TimeUtils.getTime().equals("00:00:01") ){
                isRefreshDay = true;
            }

            if (isRefreshDay) {
                isRefreshDay = false;
                tv_day.setText(TimeUtils.getDate() + "  " + TimeUtils.getWeekDay());
            }
        }
    }


    //定时刷新WebView控件
    private void reloadWebViewTimer(int second){
        if (reloadTimerThread==null){
            reloadTimerThread = new ReloadTimerThread();
        }

        if (handler!=null) {
            handler.removeCallbacks(reloadTimerThread);
            handler.postDelayed(reloadTimerThread,second*1000);
        }
    }

    //WebView刷新线程
    public class ReloadTimerThread implements Runnable{
        @Override
        public void run() {
            reloadWebView();
        }
    }

    //webview刷新
    private void reloadWebView(){
        if (!isReloadSucces ||(isReloadSucces && constant.isInternet)) {
            clearWebViewCache();//清除缓存

//            if (webView_Url.trim().equals(  configData.getUrl_Param().trim()  )) {
//                webView.reload();
//            }
//            else {
                webView_Url = "";
                reLoadUrl();
//            }
        }
    }

    //webview重新加载地址
    public void reLoadUrl(){
        if (!webView_Url.trim().equals( configData.getUrl_Param().trim() )){
            clearWebViewCache();
            tv_teachingBuilding_and_classNumber.setText(configData.getClassNumber());
//            tv_schoolName.setText(configData.getSchoolName());
            webView_Url = configData.getUrl_Param();
            webView.loadUrl(webView_Url);

            Log.d(TAG,"加载地址："+webView_Url);
        }
    }

    //webview清除缓存
    private void clearWebViewCache(){
        webView.clearCache(true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getContext().unregisterReceiver(receiver);
        if (reloadTimerThread!=null && handler!=null){
            handler.removeCallbacks(refreshTimeThread);
            handler.removeCallbacks(reloadTimerThread);
            handler.removeCallbacks(refreshWifiStrengthThread);
            handler = null;
        }

        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webView.clearHistory();
            //从父控件中移除
            ((ViewGroup) webView.getParent()).removeView(webView);
            webView.destroy();
            webView = null;
        }
        Log.d(TAG,"onDestroy()");
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KEYCODE_BACK) && webView.canGoBack()) {
//            webView.goBack();//返回上一个网页
            webView_Url = "";
            reloadWebViewTimer(0);//直接刷新
        }
        return true;
    }

}
